// 关卡选择系统
class LevelSelectMenu {
    constructor() {
        this.isOpen = false;
        this.completedLevels = [];
        this.levelBestScores = {};
        this.saveSystem = null;
    }
    
    init(saveSystem) {
        this.saveSystem = saveSystem;
        this.createLevelSelectUI();
        this.updateLevelData();
    }
    
    createLevelSelectUI() {
        // 创建关卡选择菜单
        const levelSelectMenu = document.createElement('div');
        levelSelectMenu.id = 'levelSelectMenu';
        levelSelectMenu.className = 'menu hidden';
        levelSelectMenu.style.cssText = `
            max-width: 800px;
            max-height: 80vh;
            overflow-y: auto;
            padding: 30px;
        `;
        
        levelSelectMenu.innerHTML = `
            <h2>关卡选择</h2>
            <p>选择已解锁的关卡开始游戏</p>
            <div id="levelGrid" class="level-grid"></div>
            <div class="level-select-controls">
                <button id="levelSelectBack" class="menu-btn">返回主菜单</button>
                <button id="resetProgress" class="menu-btn danger-btn">重置进度</button>
            </div>
        `;
        
        document.getElementById('gameContainer').appendChild(levelSelectMenu);
        
        // 添加事件监听器
        document.getElementById('levelSelectBack').addEventListener('click', () => {
            this.closeLevelSelect();
        });
        
        document.getElementById('resetProgress').addEventListener('click', () => {
            this.resetProgress();
        });
        
        // 添加CSS样式
        this.addLevelSelectStyles();
    }
    
    addLevelSelectStyles() {
        const styles = document.createElement('style');
        styles.textContent = `
            .level-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
                gap: 15px;
                margin: 20px 0;
            }
            
            .level-card {
                background: linear-gradient(135deg, rgba(40, 40, 40, 0.9), rgba(60, 60, 60, 0.9));
                border: 2px solid #555;
                border-radius: 10px;
                padding: 15px;
                text-align: center;
                cursor: pointer;
                transition: all 0.3s ease;
                position: relative;
                overflow: hidden;
            }
            
            .level-card:hover {
                transform: translateY(-5px);
                border-color: #ff6b6b;
                box-shadow: 0 10px 20px rgba(255, 107, 107, 0.3);
            }
            
            .level-card.locked {
                opacity: 0.5;
                cursor: not-allowed;
                background: linear-gradient(135deg, rgba(20, 20, 20, 0.9), rgba(30, 30, 30, 0.9));
            }
            
            .level-card.locked:hover {
                transform: none;
                border-color: #555;
                box-shadow: none;
            }
            
            .level-card.completed {
                border-color: #00ff88;
            }
            
            .level-card.completed::after {
                content: '✓';
                position: absolute;
                top: 5px;
                right: 10px;
                color: #00ff88;
                font-size: 20px;
                font-weight: bold;
            }
            
            .level-number {
                font-size: 24px;
                font-weight: bold;
                color: #ff6b6b;
                margin-bottom: 8px;
            }
            
            .level-name {
                font-size: 14px;
                color: #fff;
                margin-bottom: 8px;
                font-weight: bold;
            }
            
            .level-description {
                font-size: 11px;
                color: #ccc;
                margin-bottom: 10px;
                line-height: 1.3;
            }
            
            .level-stats {
                font-size: 10px;
                color: #aaa;
                border-top: 1px solid #444;
                padding-top: 8px;
            }
            
            .level-best-score {
                color: #ffd700;
                font-weight: bold;
            }
            
            .level-select-controls {
                display: flex;
                justify-content: center;
                gap: 20px;
                margin-top: 20px;
                flex-wrap: wrap;
            }
            
            .danger-btn {
                background: linear-gradient(135deg, #ff4444, #cc3333) !important;
            }
            
            .danger-btn:hover {
                background: linear-gradient(135deg, #ff6666, #ee4444) !important;
            }
            
            .lock-icon {
                font-size: 30px;
                color: #666;
                margin-bottom: 10px;
            }
            
            @media (max-width: 600px) {
                .level-grid {
                    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                    gap: 10px;
                }
                
                .level-card {
                    padding: 10px;
                }
            }
        `;
        document.head.appendChild(styles);
    }
    
    updateLevelData() {
        if (this.saveSystem) {
            this.completedLevels = this.saveSystem.getCompletedLevels();
            this.levelBestScores = this.saveSystem.getLevelBestScores();
        }
    }
    
    openLevelSelect() {
        this.updateLevelData();
        this.renderLevelGrid();
        
        document.getElementById('levelSelectMenu').classList.remove('hidden');
        document.getElementById('startMenu').classList.add('hidden');
        this.isOpen = true;
    }
    
    closeLevelSelect() {
        document.getElementById('levelSelectMenu').classList.add('hidden');
        document.getElementById('startMenu').classList.remove('hidden');
        this.isOpen = false;
    }
    
    renderLevelGrid() {
        const levelGrid = document.getElementById('levelGrid');
        if (!levelGrid) return;
        
        levelGrid.innerHTML = '';
        
        // 获取关卡数据
        const levelManager = window.gameManager ? window.gameManager.levelManager : null;
        const levels = levelManager ? levelManager.levels : [];
        
        for (let i = 0; i < 20; i++) {
            const levelNumber = i + 1;
            const levelData = levels[i] || { name: `第${levelNumber}关`, description: '未知关卡' };
            const isCompleted = this.completedLevels.includes(levelNumber);
            // 如果完成了所有关卡，则所有关卡都解锁
            const hasCompletedAllLevels = this.completedLevels.length >= 20;
            const isUnlocked = levelNumber === 1 || 
                               this.completedLevels.includes(levelNumber - 1) || 
                               hasCompletedAllLevels;
            const bestScore = this.levelBestScores[levelNumber] || 0;
            
            const levelCard = document.createElement('div');
            levelCard.className = `level-card ${isCompleted ? 'completed' : ''} ${!isUnlocked ? 'locked' : ''}`;
            
            if (isUnlocked) {
                levelCard.addEventListener('click', () => {
                    this.startLevel(levelNumber);
                });
            }
            
            levelCard.innerHTML = `
                <div class="level-number">${isUnlocked ? levelNumber : '🔒'}</div>
                <div class="level-name">${isUnlocked ? levelData.name : '未解锁'}</div>
                <div class="level-description">${isUnlocked ? levelData.description : (
                    this.completedLevels.length >= 20 ? '所有关卡已解锁' : '完成前一关解锁'
                )}</div>
                <div class="level-stats">
                    ${isUnlocked ? `
                        <div>僵尸数量: ${levelData.zombieCount || 'Boss战'}</div>
                        <div class="level-best-score">最佳分数: ${bestScore || '未完成'}</div>
                    ` : ''}
                </div>
            `;
            
            levelGrid.appendChild(levelCard);
        }
    }
    
    startLevel(levelNumber) {
        console.log(`从关卡选择开始第${levelNumber}关`);
        
        // 隐藏所有菜单（不要显示主菜单）
        this.hideAllMenus();
        
        // 初始化游戏管理器
        if (window.gameManager) {
            // 重置游戏状态
            window.gameManager.score = 0;
            window.gameManager.levelScore = 0;
            window.gameManager.lives = 3;
            window.gameManager.gameStartTime = Date.now();
            
            // 初始化玩家
            const canvas = document.getElementById('gameCanvas');
            window.player = new Player(canvas.width / 2, canvas.height / 2);
            
            // 开始指定关卡
            window.gameManager.levelManager.startLevel(levelNumber);
            
            // 更新UI
            window.gameManager.updateScoreUI();
            
            if (window.gameEngine) {
                window.gameEngine.gameState = 'playing';
            }
            
            console.log(`游戏已开始 - 关卡 ${levelNumber}`);
        }
    }
    
    // 隐藏所有菜单
    hideAllMenus() {
        const menus = [
            'levelSelectMenu',
            'startMenu', 
            'gameOverMenu',
            'levelCompleteMenu',
            'saveManageMenu',
            'achievementsMenu',
            'upgradeStoreMenu',
            'skillTreeMenu'
        ];
        
        menus.forEach(menuId => {
            const menu = document.getElementById(menuId);
            if (menu) {
                menu.classList.add('hidden');
            }
        });
        
        this.isOpen = false;
        console.log('所有菜单已隐藏');
    }
    
    resetProgress() {
        const confirmReset = confirm('确定要重置所有游戏进度吗？此操作不可撤销！\n\n这将删除：\n- 所有关卡进度\n- 最佳分数记录\n- 解锁状态\n- 统计数据');
        
        if (confirmReset) {
            try {
                // 清除所有相关的localStorage数据
                const keysToRemove = [];
                for (let i = 0; i < localStorage.length; i++) {
                    const key = localStorage.key(i);
                    if (key && (key.includes('zombieSchool') || key.includes('zombieGame'))) {
                        keysToRemove.push(key);
                    }
                }
                
                keysToRemove.forEach(key => {
                    localStorage.removeItem(key);
                });
                
                // 重置存储管理器
                if (window.storageManager) {
                    window.storageManager = new StorageManager();
                }
                
                // 重置存档系统
                if (this.saveSystem) {
                    this.saveSystem.stopAutoSave();
                    this.saveSystem = new SaveSystem();
                }
                
                // 更新关卡数据
                this.updateLevelData();
                this.renderLevelGrid();
                
                alert('游戏进度已重置！');
                
            } catch (error) {
                console.error('重置进度失败:', error);
                alert('重置失败，请刷新页面后重试。');
            }
        }
    }
    
    // 检查是否所有关卡都已完成
    isGameCompleted() {
        return this.completedLevels.length >= 20;
    }
    
    // 获取解锁的关卡数量
    getUnlockedLevelsCount() {
        if (this.completedLevels.length === 0) return 1; // 第一关始终解锁
        return Math.min(20, Math.max(...this.completedLevels) + 1);
    }
    
    // 获取完成进度百分比
    getCompletionPercentage() {
        return Math.floor((this.completedLevels.length / 20) * 100);
    }
}